package com.java.androidmarket.interceptor;

import com.alibaba.fastjson.JSON;
import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.java.androidmarket.entity.Result;
import com.java.androidmarket.utils.JWTUtils;
import com.java.androidmarket.utils.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * description:
 * author:张腾
 * date:2021-04-25
 */
@Component
public class  JWTInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisUtils redisUtils;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Result result = new Result();
        //获取请求头中的token
        if (request.getMethod().equals("OPTIONS")){
            response.setStatus(HttpServletResponse.SC_OK);
            return true;
        }
        String token = request.getHeader("Token");
        try {
            JWTUtils.verify(token);
            String userId = JWTUtils.DecodedGetID(token);
            if (redisUtils.get("Token"+userId)!=null){
                if (!redisUtils.get("Token"+userId).equals(token)) {
                    result.setCode("-999").setMsg("账号在别处登录！");
                }else{
                    return true;
                }
            }
        }catch (SignatureVerificationException e){
            e.printStackTrace();
            result.setCode("-99").setMsg("无效签名！");
        } catch (TokenExpiredException e){
            e.printStackTrace();
            result.setCode("-99").setMsg("token过期！");
        }catch (AlgorithmMismatchException e){
            e.printStackTrace();
            result.setCode("-99").setMsg("token算法不一致！");
        } catch (Exception e){
            e.printStackTrace();
            System.out.println(request.getServletPath());
            result.setCode("-99").setMsg("token无效！");
        }
        String json = JSON.toJSONString(result);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().println(json);
        return false;
    }
}
